<template>
  <view class="container">
    <!-- 显示当前日期和接单数量 -->
    <view class="header">
      <view class="date-info">
        <text>{{ currentDate }}</text>
        <text>今日接单: {{ orderCount }}</text>
      </view>
      <button @click="openCalendar" class="calendar-btn">选择日期</button>
    </view>

    <!-- uni-ui 日历组件 -->
    <uni-calendar 
      ref="calendar"
      :insert="false"
      @confirm="confirmDate"
      />

    <!-- 订单列表 -->
    <view class="order-list">
      <template v-for="(group, date) in groupedOrders" :key="date">
        <view class="date-group">
          <view class="group-header">
            <text class="group-date">{{ date }}</text>
            
          </view>
          <view class="order-item" v-for="item in group" :key="item.id" @click="handleItemClick(item)">
            <view class="item-content">
              <text class="item-title">{{ item.title }}</text>
              <text class="item-time">{{ item.time }}</text>
              <button class="delete-btn" @click="handleGroupDelete(date)">删除</button>
            </view>
          </view>
        </view>
      </template>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'  // 新增這行引入
// 当前日期
const currentDate = ref(formatDate(new Date()))
// 接单数量
const orderCount = ref(0)
// 日历组件引用
const calendar = ref()

// 定义订单项接口
interface OrderItem {
  id: string;
  title: string;
  time: string;
}

// 订单列表数据
const orderList = ref<OrderItem[]>([
  {
    id: '1',
    title: '订单示例1',
    time: '09:00'
  },
  {
    id: '2',
    title: '订单示例2',
    time: '14:30'
  }
])

// 下拉刷新處理函數
onPullDownRefresh(() => {  // 修改這裡：直接使用onPullDownRefresh
    // refreshUserInfo()
    setTimeout(() => // 完成後停止下拉刷新
    uni.stopPullDownRefresh(), 500)
})

// 格式化日期函数
function formatDate(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 打开日历
const openCalendar = () => {
  calendar.value.open()
}

// 处理点击项目
const handleItemClick = (item: OrderItem) => {
  console.log('点击了项目:', item)
}

// 处理删除
const handleDelete = (id: string) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这条记录吗？',
    success: (res) => {
      if (res.confirm) {
        orderList.value = orderList.value.filter(item => item.id !== id)
        // 这里可以添加删除接口调用
        // deleteOrder(id)
      }
    }
  })
}

// 获取订单数量（示例函数）
const getOrderCount = (date: string) => {
  // 这里添加实际的接口调用
  uni.request({
    url: 'your-api-url',
    method: 'GET',
    data: {
      date: date
    },
    success: (res) => {
      orderCount.value = res.data.count || 0
    }
  })
}

// 获取订单列表（示例函数）
const getOrderList = (date: string) => {
  // 这里添加实际的接口调用
  uni.request({
    url: 'your-api-url/orders',
    method: 'GET',
    data: { date },
    success: (res) => {
      orderList.value = res.data || []
    }
  })
}

// 修改 confirmDate 函数，添加获取列表
const confirmDate = (e: { fulldate: string }) => {
  currentDate.value = e.fulldate
  getOrderCount(e.fulldate)
  getOrderList(e.fulldate)
} 

// 计算属性：按日期分组的订单
const groupedOrders = computed(() => {
  const groups: { [key: string]: OrderItem[] } = {}
  orderList.value.forEach(order => {
    const date = order.time.split(' ')[0] // 假设time格式为 "YYYY-MM-DD HH:mm"
    if (!groups[date]) {
      groups[date] = []
    }
    groups[date].push(order)
  })
  return groups
})

// 处理组删除
const handleGroupDelete = (date: string) => {
  uni.showModal({
    title: '提示',
    content: `确定要删除 ${date} 的所有记录吗？`,
    success: (res) => {
      if (res.confirm) {
        orderList.value = orderList.value.filter(item => !item.time.startsWith(date))
        // 这里可以添加批量删除接口调用
        // deleteOrdersByDate(date)
      }
    }
  })
}

// 初始化时获取今日订单数量和订单列表
// getOrderCount(currentDate.value)
// getOrderList(currentDate.value)
</script>

<style lang="scss">
.container {
  padding: 20rpx;

  .header {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .date-info {
      display: flex;
      flex-direction: row;
      gap: 10rpx;
      color: #444;
      font-size: 30rpx;
      font-weight: 500;
    }

    .calendar-btn {
      background-color: #00B26A;
      color: #fff;
      padding: 8rpx 20rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      line-height: 1.8;
      margin: 0;
    }
  }

  .order-list {
    margin-top: 20rpx;
    
    .date-group {
      margin-bottom: 20rpx;
      background-color: #fff;
      border-radius: 8rpx;
      overflow: hidden;
      
      .group-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background-color: #f8f8f8;
        
        .group-date {
          font-size: 28rpx;
          color: #666;
          font-weight: 500;
        }
        
        
      }
      
      .order-item {
        padding: 20rpx;
        border-bottom: 1rpx solid #eee;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 20rpx;
          .delete-btn {
                font-size: 24rpx;
                color: #f5f5f5;
                background: none;
                color: #333;
                border: none;
                padding: 4rpx 16rpx;
                margin: 0;
                &:active {
                    opacity: 0.8;
                }
            }
          .item-title {
            font-size: 28rpx;
            color: #333;
          }
          
          .item-time {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }
}
</style>